package main

import (
	"context"
	"os"

	pb "demo/helloworld"
	"demo/pkg/tracex"

	"github.com/go-kratos/kratos/v2/log"

	"github.com/go-kratos/kratos/v2/middleware/recovery"
	"github.com/go-kratos/kratos/v2/middleware/tracing"
	transgrpc "github.com/go-kratos/kratos/v2/transport/grpc"
	grpc "google.golang.org/grpc"
)

func main() {
	callGRPC()
}

func callGRPC() {
	logger := log.NewStdLogger(os.Stdout)
	logger = log.With(logger, "trace_id", tracing.TraceID())
	logger = log.With(logger, "span_id", tracing.SpanID())
	logg := log.NewHelper(logger)

	url := "http://jaeger:14268/api/traces"
	if os.Getenv("jaeger_url") != "" {
		url = os.Getenv("jaeger_url")
	}
	err := tracex.SetJaegerServerTracer("demo", "local", url)
	if err != nil {
		logg.Error(err)
	}

	conn, err := transgrpc.DialInsecure(
		context.Background(),
		transgrpc.WithEndpoint("127.0.0.1:9000"),
		transgrpc.WithMiddleware(
			recovery.Recovery(),
			tracing.Client(),
		),
	)
	if err != nil {
		panic(err)
	}
	defer func(conn *grpc.ClientConn) {
		_ = conn.Close()
	}(conn)
	client := pb.NewGreeterClient(conn)
	reply, err := client.SayHello(context.Background(), &pb.HelloRequest{Name: "kratos"})
	if err != nil {
		log.Fatal(err)
	}
	logg.Infof("[grpc] SayHello %+v\n", reply)

	// returns error
	//_, err = client.SayHello(context.Background(), &pb.HelloRequest{Name: "error"})
	//if err != nil {
	//	logg.Infof("[grpc] SayHello error: %v\n", err)
	//}
	//if errors.IsBadRequest(err) {
	//	logg.Infof("[grpc] SayHello error is invalid argument: %v\n", err)
	//}
}
